﻿#region <!-- Using Directives -->

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;

#endregion

namespace WordSharpDev.Extensions
{
	internal static class StringExtensions
	{
		#region <!-- IsVoid -->

		public static Boolean IsVoid(this String p_This)
		{
			if (p_This == null) return true;

			if (p_This.Trim(' ', '\t', '\r', '\n') == "") return true;

			return false;
		}

		#endregion

		#region <!-- Left -->

		public static String Left(this String p_This, Int32 p_Count)
		{
			if (p_This == null) return null;

			if (p_Count < 0) p_Count = p_This.Length + p_Count;

			if (p_This.Length <= p_Count) return p_This;

			if (p_Count <= 0) return "";

			return p_This.Substring(0, p_Count);
		}

		#endregion

		#region <!-- Right -->

		public static String Right(this String p_This, Int32 p_Count)
		{
			if (p_This == null) return null;

			if (p_Count < 0) p_Count = p_This.Length + p_Count;

			if (p_This.Length <= p_Count) return p_This;

			if (p_Count <= 0) return "";

			return p_This.Substring(p_This.Length - p_Count, p_Count);
		}

		#endregion

		#region <!-- Indent -->

		public static String Indent(this String p_This, String p_Indent)
		{
			if (p_This == null) return null;

			var l_Result = "";
			var l_Separator = "";

			foreach (var i_Line in p_This.Split('\r', '\n'))
			{
				if (!i_Line.IsVoid())
				{
					l_Result += l_Separator + String.Format("{0}{1}", p_Indent, i_Line);

					l_Separator = "\r\n";
				}
			}

			return l_Result;
		}

		#endregion

		#region <!-- GetChars -->

		public static IEnumerable<String> GetChars(this String p_This)
		{
			var i = 0;

			while (true)
			{
				if (p_This.Length <= i) break;

				var c = p_This[i++];

				if (Char.IsHighSurrogate(c))
				{
					var d = p_This[i++];

					if (Char.IsLowSurrogate(d))
					{
						if (c == 0xD835 && 0xDC4E <= d && d <= 0xDC67)
						{
							yield return Char.ConvertFromUtf32(d - 0xDC4E + 'a');
						}
						else
						{
							yield return Char.ConvertFromUtf32(Char.ConvertToUtf32(c, d));							
						}
					}
				}
				else
				{
					yield return c.ToString();
				}
			}
		}

		#endregion
	}
}